<script>
	var commonCounter = 0;
	var totalPrice = 0;
	var itemCode = {}, itemName = {}, batchId = {}, mfd = {}, exp = {}, boughtPrice = {}, unitPrice = {}, quantity = {},objCounter = {},oldAmount = {},newAmount = {};
	function validate(i){
		var mfd = $('#mfd'+i).val();
		var exp = $('#exp'+i).val();
		if ($("#batchId"+i+" option:selected").val() == 0){
			$("#messages").html("<div id='msg1' title='Indika Stores'>Batch date is required.");
			//$( "#msg1" ).dialog();
			$( "#msg1" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
		}else if($('#boughtPrice'+i).val() == '' ){
			$("#messages").html("<div id='msg2' title='Indika Stores'>bought price is required.");
			//$( "#msg2" ).dialog();
			$( "#msg2" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
		}else if($('#unitPrice'+i).val() == '' ){
			$("#messages").html("<div id='msg3' title='Indika Stores'>Selling price is required.");
			//$( "#msg3" ).dialog();
			$( "#msg3" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
		}else if($('#quantity'+i).val() == '' ){
			$("#messages").html("<div id='msg4' title='Indika Stores'>Quantity is required.");
			//$( "#msg4" ).dialog();
			$( "#msg4" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
		}else if(mfd == '' && mfd == ''){
				addToStock(i);
		}else if(mfd == '' && exp != ''){
			if(checkDateFormat(exp))
				addToStock(i);
		}else if(mfd != '' && exp == ''){
			if(checkDateFormat(mfd))
				addToStock(i);
		}else if(mfd != '' && exp != ''){
			if(checkDateFormat(mfd) && checkDateFormat(exp)){
				if(Date.parse(mfd) < Date.parse(exp))
					addToStock(i);
				else{
					$("#messages").html("<div id='msg5' title='Indika Stores'>Expiry date must be greater than manufacture date.");
					//$( "#msg5" ).dialog();
					$( "#msg5" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
				}
			}
		}
	}
	
	function checkDateFormat(date){
		var pattern = /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/;   //defining pattern for date
		if (pattern.test(date)) {
			return true;
		}else{
			$("#messages").html("<div id='msg6' title='Indika Stores'>Invalid date format.Please Input in (yyyy-mm-dd) format!");
			//$( "#msg6" ).dialog();
			$( "#msg6" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
			return false;
		}
	}
	
	function numbersOnly(e, decimal) {
		var key;
		var keychar;

		if (window.event)
		   key = window.event.keyCode;
		else if (e)
		   key = e.which;
		else
		   return true;

		keychar = String.fromCharCode(key);
		if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
		   return true;
		else if ((("0123456789").indexOf(keychar) > -1))
		   return true;
		else
		   return false;
	}
	function testForEnter() {
		if (event.keyCode == 13) {        
			event.cancelBubble = true;
			event.returnValue = false;
		}
	}
	
	function addToStock(i){
		itemCode['itemcode' + i] = $('#itemCode'+i).text();
		itemName['itemname' + i] = $('#itemName'+i).text();
		batchId['batchid' + i] = $("#batchId"+i+" option:selected").val();
		mfd['mfd' + i] = $("#mfd"+i).val();
		exp['exp' + i] = $("#exp"+i).val();
		boughtPrice['boughtprice' + i] = parseFloat($("#boughtPrice"+i).val());
		unitPrice['unitprice' + i] = parseFloat($("#unitPrice"+i).val());
		quantity['quantity'+i] = parseFloat($("#quantity"+i).val());
		
		if(!objCounter['objcounter'+i]){
			objCounter['objcounter' + i] = 1;
		}
		
		if(commonCounter == 0){
			var newRow = $(	"<tr><th>Item Name</th><th>Quantity</th><th>Amount</th><th>Delete</th></tr>");
			$('table.cart').append(newRow);
			commonCounter++;
		}
		if(objCounter['objcounter' + i] == 1){
			$("#displayStock #title").text("Stock Content");
			var newRow = $( "<tr id='row"+i+"'><td>"+itemName['itemname' + i]+" </td>"+
								"<td id='qtyId"+i+"'>"+quantity['quantity' + i]+"</td>"+
								"<td><div id='amount"+i+"'></div>"+
									"<input type='hidden' name='itemCode"+i+"' value='"+itemCode['itemcode' + i]+"'/>"+
									"<input type='hidden' name='batchId"+i+"' value='"+batchId['batchid' + i]+"'/>"+
									"<input type='hidden' name='mfd"+i+"' value='"+mfd['mfd' + i]+"'/>"+
									"<input type='hidden' name='exp"+i+"' value='"+exp['exp' + i]+"'/>"+
									"<input type='hidden' name='boughtPrice"+i+"' value='"+boughtPrice['boughtprice' + i]+"'/>"+
									"<input type='hidden' name='unitPrice"+i+"' value='"+unitPrice['unitprice' + i]+"'/>"+
									"<input type='hidden' name='quantity"+i+"' value='"+quantity['quantity'+i]+"'/>"+
								"</td>"+
								"<td><button type='button' id='deleteBtn' onClick='deleteRow("+i+")'></button></td>"+
							"</tr>");
			$('table.cart').append(newRow);
			$("#displayStock #amount"+i).text(quantity['quantity'+i] * boughtPrice['boughtprice' + i]+" Rs");
			newAmount['newamount'+i] = parseFloat($("#displayStock #amount"+i).text());
			objCounter['objcounter' + i] = 2;
		}else{
			$("#displayStock #qtyId"+i).text(quantity['quantity'+i]);
			oldAmount['oldamount'+i] = parseFloat($("#displayStock #amount"+i).text());
			$("#displayStock #amount"+i).text(quantity['quantity'+i] * boughtPrice['boughtprice' + i]+" Rs");
			newAmount['newamount'+i] = parseFloat($("#displayStock #amount"+i).text());
		}
		if(commonCounter > 0){
			$("#finish").html("<input id='submitBtn' type='submit' value='Add Stock'/>");
			if(objCounter['objcounter' + i] > 2)
				totalPrice += newAmount['newamount'+i] - oldAmount['oldamount'+i];
			else if(objCounter['objcounter' + i] == 2){
				totalPrice += parseFloat($("#displayStock #amount"+i).text());
				objCounter['objcounter' + i]++;
			}
			$("#total").text("Total Price : "+totalPrice+" Rs/=");
		}
		dTable.fnFilter('');
	}
	
	function deleteRow(i){
		objCounter['objcounter' + i] = 1;
		totalPrice = totalPrice - newAmount['newamount'+i];
		$("#total").text("Total Price : "+totalPrice+" Rs/=");
		$("#row"+i).remove();
	}
</script>
<?php include './pages/stockMenu.php'; ?>
<div id="addStock">
	<div id="stockTable">
		<?php
			if (!isset($_SESSION)) {
				 session_start();
			}
			include("./system/dbconnection.php");
			if($result = mysql_query("SELECT itemCode, itemName FROM  `items` ")){
				$num = mysql_num_rows($result);
				$_SESSION['num'] =  $num;
			}else{
				$_SESSION['error'] = "Error occured ";
			}
			if(isset($_SESSION['success']) && $_SESSION['success'] != "") {  
				echo '<div id="success" title="Indika Stores">'.$_SESSION['success'].'</div>';
				echo '<script type=\'text/javascript\'>';
				echo '$( "#success" ).dialog();';
				echo '$( "#success" ).dialog({buttons: { "Close": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 400 });';  
				echo '</script>';   
			}else if(isset($_SESSION['error']) && $_SESSION['error'] != "") {  
				echo '<div id="error" title="Indika Stores">'.$_SESSION['error'].'</div>';
				echo '<script type=\'text/javascript\'>';
				echo '$( "#error" ).dialog();';
				echo '$( "#error" ).dialog({buttons: { "Close": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 450 });';  
				echo '</script>';  
			}  
		?>
		<table border="1" cellpadding="2" class="dataTable" style="width:100%">
			<thead>
				<tr>
					<th>Item Code</th><th>Item Name</th><th>Batch Date</th><th>MFD</th><th>EXP</th><th>Bought Price</th><th>Price</th><th>Quantity</th><th>Add</th>
				</tr>
			</thead>
			<tbody>
			<?php
				$i=0;
				while ($i < $num) {
					$f1=mysql_result($result,$i,"itemCode");
					$f2=mysql_result($result,$i,"itemName");
			?>
				<tr>
					<td id="itemCode<?php echo $i ?>"><?php echo $f1; ?></td>
					<td id="itemName<?php echo $i ?>"><?php echo $f2; ?></td>
					<td>
						<select id="batchId<?php echo $i ?>" style="width:95px">
							<option value="0">Select</option>
							<?php 
							if($res = mysql_query("SELECT * FROM batches ORDER BY batchId DESC LIMIT 3")){
								while($row = mysql_fetch_assoc($res)){
									echo "<option value='".$row['batchId']."'>".$row['batchDate']."</option>";
								}
							} 
							?>
						</select>
					</td>
					<td><input type="text" name="mfd" class="datePicker" size="8" id="mfd<?php echo $i ?>"  /></td>
					<td><input type="text" name="exp" class="datePicker" size="8" id="exp<?php echo $i ?>" /></td>
					<td><input type="text" size="5" class="boughtPrice" id="boughtPrice<?php echo $i ?>" onkeypress="return numbersOnly(event, true);  if (event.keyCode == 13) document.getElementById('addBtn<?php echo $i ?>').click();"/></td>
					<td><input type="text" size="5" class="unitPrice" id="unitPrice<?php echo $i ?>" onkeypress="return numbersOnly(event, true);  if (event.keyCode == 13) document.getElementById('addBtn<?php echo $i ?>').click()"/></td>
					<td><input type="text" size="5" class="quantity" id="quantity<?php echo $i ?>" onkeypress="return numbersOnly(event, true);  if (event.keyCode == 13) document.getElementById('addBtn<?php echo $i ?>').click()"/></td>
					<td id='add'><input type="button" value="Add" id="addBtn<?php echo $i ?>" onclick="validate(<?php echo $i ?>)"/></td>
				</tr>
			<?php
					$i++;
				}
			?>
			</tbody>
		</table>
		<div id="messages"></div>
	</div>
	<div id='form'>
		<form action='./system/action/addStock.php' method='post'>
			<div id="displayStock">
				<div id="title">New Stocks</div>
				<table id="cart" border="1" cellpadding="2" cellspacing="0" class="cart" style="text-align: center"></table>
			</div>
			<div id='bill'>
				<div id="total"></div>
				<div id="finish"></div>
			</div>
		</form>
	</div>
</div>